package com.cnbbx.mybatis.query.builder;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.cnbbx.mybatis.definition.EntityColumnDefinition;
import com.cnbbx.mybatis.definition.EntityDefinition;
import com.cnbbx.mybatis.definition.Update;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class InsertBuilder extends BaseQuery {
    private List<Update> updates = new ArrayList<Update>();

    protected InsertBuilder(Class clazz) {
        super(clazz);
    }

    public static InsertBuilder build(Class clazz) {
        return new InsertBuilder(clazz);
    }

    public List<Update> getUpdates() {
        return updates;
    }

    public void setUpdates(List<Update> updates) {
        this.updates = updates;
    }

    public InsertBuilder set(Object object) {
        if (!getClazz().equals(object.getClass())) {
            throw new RuntimeException("不支持该类");
        }
        EntityDefinition entityDefinition = findEntityDefinition();
        List<Field> all = allFields(getClazz());
        for (Field field : all) {
            EntityColumnDefinition entityColumnDefinition = entityDefinition.getColumnDefinitions().get(field.getName());
            if (entityColumnDefinition != null) {
                try {
                    JSONObject obj = (JSONObject) JSON.toJSON(object);
                    if (obj != null) {
                        set(entityColumnDefinition.getJavaColumn(), obj.get(entityColumnDefinition.getJavaColumn()));
                    }
                } catch (Exception e) {
                    log.error("set field error:", e);
                }
            }
        }
        return this;
    }

    public InsertBuilder set(String property, Object value) {
        set(property, value, updates, this);
        return this;
    }
}
